import React, { useState, useEffect, useRef } from 'react'
import {
  Card,
  List,
  Input,
  Select,
  Button,
  Space,
  Typography,
  Tag,
  Tooltip,
  Empty,
  Spin,
  Switch,
  Badge,
  Drawer,
  Descriptions,
} from 'antd'
import {
  SearchOutlined,
  ReloadOutlined,
  DownloadOutlined,
  FilterOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons'
import { formatDateTime, formatDuration } from '@/utils'

const { Search } = Input
const { Option } = Select
const { Text, Paragraph } = Typography

export interface LogEntry {
  id: string
  timestamp: string
  level: 'info' | 'warn' | 'error' | 'debug'
  message: string
  execution_id?: string
  connection_id?: string
  connection_name?: string
  user_id?: string
  user_name?: string
  duration?: number
  sql?: string
  error_details?: string
  metadata?: Record<string, any>
}

interface ExecutionLogsProps {
  logs: LogEntry[]
  loading?: boolean
  onRefresh?: () => void
  onExport?: () => void
  onLoadMore?: () => void
  hasMore?: boolean
  autoRefresh?: boolean
  onAutoRefreshChange?: (enabled: boolean) => void
  maxHeight?: number
}

const ExecutionLogs: React.FC<ExecutionLogsProps> = ({
  logs,
  loading = false,
  onRefresh,
  onExport,
  onLoadMore,
  hasMore = false,
  autoRefresh = false,
  onAutoRefreshChange,
  maxHeight = 600,
}) => {
  const [searchText, setSearchText] = useState('')
  const [levelFilter, setLevelFilter] = useState<string>('')
  const [connectionFilter, setConnectionFilter] = useState<string>('')
  const [selectedLog, setSelectedLog] = useState<LogEntry | null>(null)
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false)
  const [autoScroll, setAutoScroll] = useState(true)
  const listRef = useRef<HTMLDivElement>(null)

  // 自动刷新
  useEffect(() => {
    if (!autoRefresh) return

    const interval = setInterval(() => {
      onRefresh?.()
    }, 5000) // 每5秒刷新一次

    return () => clearInterval(interval)
  }, [autoRefresh, onRefresh])

  // 自动滚动到底部
  useEffect(() => {
    if (autoScroll && listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight
    }
  }, [logs, autoScroll])

  // 过滤日志
  const filteredLogs = logs.filter(log => {
    const matchesSearch = !searchText || 
      log.message.toLowerCase().includes(searchText.toLowerCase()) ||
      log.sql?.toLowerCase().includes(searchText.toLowerCase()) ||
      log.connection_name?.toLowerCase().includes(searchText.toLowerCase())
    
    const matchesLevel = !levelFilter || log.level === levelFilter
    const matchesConnection = !connectionFilter || log.connection_id === connectionFilter
    
    return matchesSearch && matchesLevel && matchesConnection
  })

  // 获取日志级别图标和颜色
  const getLevelConfig = (level: string) => {
    switch (level) {
      case 'error':
        return {
          icon: <CloseCircleOutlined />,
          color: '#f5222d',
          bgColor: '#fff2f0',
          borderColor: '#ffccc7',
        }
      case 'warn':
        return {
          icon: <WarningOutlined />,
          color: '#faad14',
          bgColor: '#fffbe6',
          borderColor: '#ffe58f',
        }
      case 'info':
        return {
          icon: <InfoCircleOutlined />,
          color: '#1890ff',
          bgColor: '#f0f9ff',
          borderColor: '#bae7ff',
        }
      case 'debug':
        return {
          icon: <CheckCircleOutlined />,
          color: '#52c41a',
          bgColor: '#f6ffed',
          borderColor: '#b7eb8f',
        }
      default:
        return {
          icon: <InfoCircleOutlined />,
          color: '#666',
          bgColor: '#f5f5f5',
          borderColor: '#d9d9d9',
        }
    }
  }

  // 获取唯一连接列表
  const uniqueConnections = Array.from(
    new Set(logs.map(log => log.connection_id).filter(Boolean))
  ).map(id => {
    const log = logs.find(l => l.connection_id === id)
    return { id, name: log?.connection_name || id }
  })

  // 处理查看详情
  const handleViewDetail = (log: LogEntry) => {
    setSelectedLog(log)
    setDetailDrawerVisible(true)
  }

  // 渲染日志项
  const renderLogItem = (log: LogEntry) => {
    const levelConfig = getLevelConfig(log.level)
    
    return (
      <List.Item
        key={log.id}
        style={{
          borderLeft: `4px solid ${levelConfig.color}`,
          backgroundColor: levelConfig.bgColor,
          border: `1px solid ${levelConfig.borderColor}`,
          borderRadius: 4,
          margin: '4px 0',
          padding: '8px 12px',
        }}
        actions={[
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(log)}
            />
          </Tooltip>,
        ]}
      >
        <List.Item.Meta
          avatar={
            <div style={{ 
              color: levelConfig.color, 
              fontSize: 16,
              marginTop: 2,
            }}>
              {levelConfig.icon}
            </div>
          }
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Tag color={levelConfig.color} style={{ margin: 0 }}>
                {log.level.toUpperCase()}
              </Tag>
              <Text style={{ fontSize: 12, color: '#666' }}>
                {formatDateTime(log.timestamp)}
              </Text>
              {log.connection_name && (
                <Text style={{ fontSize: 12, color: '#666' }}>
                  {log.connection_name}
                </Text>
              )}
              {log.user_name && (
                <Text style={{ fontSize: 12, color: '#666' }}>
                  {log.user_name}
                </Text>
              )}
              {log.duration && (
                <Space size={4}>
                  <ClockCircleOutlined style={{ fontSize: 11, color: '#666' }} />
                  <Text style={{ fontSize: 11, color: '#666' }}>
                    {formatDuration(log.duration)}
                  </Text>
                </Space>
              )}
            </div>
          }
          description={
            <div>
              <Paragraph
                ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
                style={{ 
                  margin: 0, 
                  fontSize: 13,
                  color: '#333',
                }}
              >
                {log.message}
              </Paragraph>
              
              {log.sql && (
                <div style={{ 
                  marginTop: 8,
                  padding: '6px 8px',
                  background: 'rgba(0,0,0,0.02)',
                  borderRadius: 4,
                  fontFamily: 'Monaco, Consolas, monospace',
                  fontSize: 11,
                  color: '#666',
                }}>
                  <Paragraph
                    ellipsis={{ rows: 1, expandable: true, symbol: '展开SQL' }}
                    style={{ margin: 0 }}
                  >
                    {log.sql}
                  </Paragraph>
                </div>
              )}
              
              {log.error_details && (
                <div style={{ 
                  marginTop: 8,
                  padding: '6px 8px',
                  background: '#fff2f0',
                  border: '1px solid #ffccc7',
                  borderRadius: 4,
                  fontSize: 11,
                  color: '#f5222d',
                }}>
                  <Paragraph
                    ellipsis={{ rows: 1, expandable: true, symbol: '展开错误' }}
                    style={{ margin: 0 }}
                  >
                    {log.error_details}
                  </Paragraph>
                </div>
              )}
            </div>
          }
        />
      </List.Item>
    )
  }

  return (
    <div>
      <Card 
        title={
          <Space>
            <span>执行日志</span>
            <Badge count={filteredLogs.length} showZero />
          </Space>
        }
        size="small"
        extra={
          <Space>
            <Switch
              size="small"
              checked={autoScroll}
              onChange={setAutoScroll}
              checkedChildren="自动滚动"
              unCheckedChildren="手动滚动"
            />
            <Switch
              size="small"
              checked={autoRefresh}
              onChange={onAutoRefreshChange}
              checkedChildren="自动刷新"
              unCheckedChildren="手动刷新"
            />
            <Button
              type="text"
              size="small"
              icon={<ReloadOutlined />}
              onClick={onRefresh}
              loading={loading}
            >
              刷新
            </Button>
            {onExport && (
              <Button
                type="text"
                size="small"
                icon={<DownloadOutlined />}
                onClick={onExport}
              >
                导出
              </Button>
            )}
          </Space>
        }
      >
        {/* 搜索和过滤 */}
        <div style={{ marginBottom: 12 }}>
          <Space wrap>
            <Search
              placeholder="搜索日志内容..."
              style={{ width: 250 }}
              size="small"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
            
            <Select
              placeholder="日志级别"
              style={{ width: 100 }}
              size="small"
              value={levelFilter}
              onChange={setLevelFilter}
              allowClear
            >
              <Option value="error">ERROR</Option>
              <Option value="warn">WARN</Option>
              <Option value="info">INFO</Option>
              <Option value="debug">DEBUG</Option>
            </Select>
            
            <Select
              placeholder="连接"
              style={{ width: 120 }}
              size="small"
              value={connectionFilter}
              onChange={setConnectionFilter}
              allowClear
            >
              {uniqueConnections.map(conn => (
                <Option key={conn.id} value={conn.id}>
                  {conn.name}
                </Option>
              ))}
            </Select>
          </Space>
        </div>

        {/* 日志列表 */}
        <div 
          ref={listRef}
          style={{ 
            maxHeight, 
            overflow: 'auto',
            border: '1px solid #f0f0f0',
            borderRadius: 6,
            padding: 8,
          }}
        >
          {filteredLogs.length === 0 ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="暂无日志数据"
              style={{ padding: '40px 0' }}
            />
          ) : (
            <List
              dataSource={filteredLogs}
              renderItem={renderLogItem}
              loading={loading}
              size="small"
              split={false}
            />
          )}
        </div>

        {/* 加载更多 */}
        {hasMore && (
          <div style={{ textAlign: 'center', marginTop: 12 }}>
            <Button size="small" onClick={onLoadMore} loading={loading}>
              加载更多
            </Button>
          </div>
        )}
      </Card>

      {/* 详情抽屉 */}
      <Drawer
        title="日志详情"
        placement="right"
        width={600}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
      >
        {selectedLog && (
          <div>
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="时间">
                {formatDateTime(selectedLog.timestamp)}
              </Descriptions.Item>
              
              <Descriptions.Item label="级别">
                <Tag color={getLevelConfig(selectedLog.level).color}>
                  {selectedLog.level.toUpperCase()}
                </Tag>
              </Descriptions.Item>
              
              {selectedLog.execution_id && (
                <Descriptions.Item label="执行ID">
                  <Text code>{selectedLog.execution_id}</Text>
                </Descriptions.Item>
              )}
              
              {selectedLog.connection_name && (
                <Descriptions.Item label="连接">
                  {selectedLog.connection_name}
                </Descriptions.Item>
              )}
              
              {selectedLog.user_name && (
                <Descriptions.Item label="用户">
                  {selectedLog.user_name}
                </Descriptions.Item>
              )}
              
              {selectedLog.duration && (
                <Descriptions.Item label="耗时">
                  {formatDuration(selectedLog.duration)}
                </Descriptions.Item>
              )}
              
              <Descriptions.Item label="消息">
                <div style={{ 
                  padding: 12,
                  background: '#f5f5f5',
                  borderRadius: 6,
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-word',
                }}>
                  {selectedLog.message}
                </div>
              </Descriptions.Item>
              
              {selectedLog.sql && (
                <Descriptions.Item label="SQL语句">
                  <div style={{ 
                    padding: 12,
                    background: '#f5f5f5',
                    borderRadius: 6,
                    fontFamily: 'Monaco, Consolas, monospace',
                    fontSize: 12,
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-word',
                    maxHeight: 200,
                    overflow: 'auto',
                  }}>
                    {selectedLog.sql}
                  </div>
                </Descriptions.Item>
              )}
              
              {selectedLog.error_details && (
                <Descriptions.Item label="错误详情">
                  <div style={{ 
                    padding: 12,
                    background: '#fff2f0',
                    border: '1px solid #ffccc7',
                    borderRadius: 6,
                    fontSize: 12,
                    color: '#f5222d',
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-word',
                    maxHeight: 200,
                    overflow: 'auto',
                  }}>
                    {selectedLog.error_details}
                  </div>
                </Descriptions.Item>
              )}
              
              {selectedLog.metadata && Object.keys(selectedLog.metadata).length > 0 && (
                <Descriptions.Item label="元数据">
                  <div style={{ 
                    padding: 12,
                    background: '#f5f5f5',
                    borderRadius: 6,
                    fontFamily: 'Monaco, Consolas, monospace',
                    fontSize: 12,
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-word',
                    maxHeight: 200,
                    overflow: 'auto',
                  }}>
                    {JSON.stringify(selectedLog.metadata, null, 2)}
                  </div>
                </Descriptions.Item>
              )}
            </Descriptions>
          </div>
        )}
      </Drawer>
    </div>
  )
}

export default ExecutionLogs